/*
    Static JS for Analysis functionality
*/

// Global vars
var analysisColors = ['#949494', '#df09b7', '#1384ae'];
var analysisDataCache = {};
var analysisGraphHoverable = true;
var analysisLineGraph = null;
var analysisLocation = {0: null, 1: null, 2: null, 3: null};
var analysisTooltipPreviousPoint = null;
var analysisTooltipPreviousSeries = null;

function analysisView() {
    // Close any open Popups
    closePopups();
    if (drawerOpen) {
        // Close Drawer
        drawerSlide();
    }
    // Hide the drawer
    $('#drawer').hide();
    // Hide the Reports/Submit Data menus
    $('#dataTopBar').hide();
    $('#reportsTopBar').hide();
    // Update and open the Analysis section
    analysisUpdateSelectedLocations();
    toggleAnalysis();
    $('#analysis').show();
}

function hideAnalysis() {
    // Reset the graph and hide the tooltip box
    analysisResetGraph();
    // Close the Analysis section
    $('#analysis').hide();
    // Show the Reports/Submit Data menus
    $('#dataTopBar').show();
    $('#reportsTopBar').show();
    // Show Drawer
    $('#drawer').show();
}

function toggleAnalysis() {
    // Switch between Overall Resilience & Indicator Comparison
    if ($('#analysisIndicator').val() == 'overall') {
        analysisResetGraph();
        analysisUpdateGraph();

        $('#treeMapDescription').hide();
        $('.treeMapContainer').hide();

        $('#lineGraphDescription').show();
        $('#analysisControl1, #analysisControl2, #analysisControl3').show();
        $('.lineGraphContainer').show();
        $('#analysisTimeline').show();
        $('.eventMarkers').show();
        $('#analysisTimelineContainer').show();

    } else {
        analysisResetGraph();

        $('#lineGraphDescription').hide();
        $('#analysisControl1, #analysisControl2, #analysisControl3').hide();
        $('.lineGraphContainer').hide();
        $('#analysisTimeline').hide();
        $('.eventMarkers').hide();
        $('#analysisTimelineContainer').hide();

        $('#treeMapDescription').show();
        $('.treeMapContainer').show();

        // Get the current location
        var location = analysisLocation[1]['id'];

        // Update the tree map for this location and indicator
        tmGoToLocation(location);
    }
}

function analysisReset(id) {
    // Reset the Hierarchy widget
    $('#l0_analysis' + id + 's').val('');
    $('#l1_analysis' + id).hide();
    $('#l2_analysis' + id).hide();
    $('#l3_analysis' + id).hide();
    //$('#l4_analysis' + id).hide();
    // Update style
    var selected = $('#analysisControl' + id + ' select');
    try {
        selected.selectmenu('destroy');
    } catch(err) {}
    selected.selectmenu({
        style: 'popup',
        maxHeight: 280,
        width: 125,
        menuWidth: 125
    });
    analysisSelectLocation(null, id);
}

function analysisResetGraph() {
    // Remove the tooltip
    $('#analysisTooltip').remove();
    // Hide the region indicator breakdown
    $('#regionIndicators').hide();
    // Reset hoverable-status (only effective after updateGraph!)
    analysisGraphHoverable = true;
    analysisTooltipPreviousSeries = null;
    analysisTooltipPreviousPoint = null;
    $('h5.analysisSeriesLabel').unbind('hover');
    $('#analysisLineGraph').unbind('plothover');
    $('#analysisLineGraph').unbind('plotclick');
}

function analysisUpdateSelectedLocations() {
    // Read the currently selected locations from the hierarchical
    // drop-down and update analysisLocation, then update the graph.
    // This should be called when opening the analysis view

    for (var n=1; n <= 3; n++) {
        analysisLocation[n] = null;
        for (var l=4; l >= 0; l--) {
            var id = $('#l' + l + '_analysis' + n + 's').val();
            if (typeof id == 'undefined' || id === '' || id === null) {
                continue;
            } else {
                if (id !== null && vdata.hasOwnProperty(id)) {
                    var h = hdata[$('#l0_analysis' + n + 's').val()];
                    var ln = vdata[id]['l'];
                    var level;
                    if (ln === 0) {
                        level = i18n.country;
                    } else {
                        level = h['l' + ln];
                    }
                    analysisLocation[n] = {
                        id: id,
                        name: vdata[id]['n'],
                        level: level
                    };
                    break;
                }
            }
        }
    }
    analysisGetData();
}

function analysisSelectLocation(id, series) {
    // Select a location for the resilience history line graph
    // id = the location ID, series = the data series (1, 2 or 3)
    // This should be called when a location gets selected in the
    // hierarchical drop-down (=lx_select) or reset

    var previousLocation = analysisLocation[series];
    if (previousLocation !== null && previousLocation['id'] == id) {
        return; // unchanged
    }
    if (id !== null && vdata.hasOwnProperty(id)) {
        var h = hdata[$('#l0_analysis' + series + 's').val()];
        var l = vdata[id]['l'];
        var level;
        if (l === 0) {
            level = i18n.country;
        } else {
            level = h['l' + l];
        }
        analysisLocation[series] = {
            id: id,
            name: vdata[id]['n'],
            level: level
        };
    } else {
        // Reset
        analysisLocation[series] = null;
    }
    analysisGetData();
}

function analysisGetData() {
    // Get the data for the currently selected location, load them from
    // the server if necessary
    // This is called whenever analysisLocation gets updated for any series

    analysisResetGraph();

    var url = S3.Ap.concat('/vulnerability/rdata');

    if (analysisLocation[1] === null) {
        analysisLocation[1] = analysisLocation[0];
    }

    // Check whether we have all the data in the cache
    var load = false;
    for (n=1; n <= 3; n++) {
        var location = analysisLocation[n];
        if (location === null) {
            continue;
        } else {
            var location_id = location['id'];
            var data = analysisDataCache[location_id];
            if (typeof data == 'undefined') {
                // Duplicates irrelevant here - controller will sort it out
                url += '/' + location_id;
                load = true;
            }
        }
    }

    if (load) {
        // Need to load data from the server
        // => load asynchronously and call updateGraph upon success
        $.ajax({
            'url': url,
            'success': function(data) {
                for (var location_id in r) {
                    analysisDataCache[location_id] = r[location_id];
                }
                analysisUpdateGraph();
            },
            'error': function(request, status, error) {
                // @todo: can this be unauthorized?
                if (error == 'UNAUTHORIZED') {
                    msg = i18n.gis_requires_login;
                } else {
                    msg = request.responseText;
                }
                console.log(msg);
            },
            'dataType': 'script'
        });
    } else {
        // All data in cache, can update graph synchronously
        analysisUpdateGraph();
    }
}

function analysisUpdateGraph() {
    // (Re-)draw the line graph

    var show_deviation = true; // can turn off deviation shadow area

    // The line graph can render any of the indicators, but this
    // isn't currently part of the design. Once it is, then this
    // is the variable to set:
    // var indicator_index = $('#analysisIndicator').val();

    var indicator_index = 0; // 0 = overall resilience

    // Transform the data into series
    var analysisData = {1: null, 2: null, 3: null};
    for (var n=1; n <= 3; n++) {
        var location = analysisLocation[n];
        if (location === null) {
            continue;
        } else {
            var location_id = location['id'];
            analysisData[n] = {label: location['name']};
            var location_data = analysisDataCache[location_id];
            var value = [];
            var upper = [];
            var lower = [];
            for (var y in location_data) {
                var d = location_data[y][indicator_index];
                if (typeof d == 'undefined') {
                    // Workaround for missing mean:
                    // @todo: we should not have to compute that here,
                    // server should make sure that there always is a mean
                    if (indicator_index === 0) {
                        sum = 0.0;
                        len = 0.0;
                        for (var i=1; i <= 10; i++) {
                            p = location_data[y][i];
                            if (typeof p != 'undefined') {
                                sum += Number(p[0]);
                                len += 1.0;
                            }
                        }
                        if (len !== 0) {
                            // @todo: deviation is set to 0 here, which is obviously wrong
                            d = [(sum / len), 0.0];
                            analysisDataCache[location_id][y]['0'] = d;
                        } else {
                            continue;
                        }
                    } else {
                        continue;
                    }
                }
                value.push([y, d[0]]);
                // Scale deviation by 2/5
                lower.push([y, d[0] - d[1]/5.0]);
                upper.push([y, d[0] + d[1]/5.0]);
            }
            analysisData[n]['name'] = location['name'];
            analysisData[n]['value'] = value;
            analysisData[n]['lower'] = lower;
            analysisData[n]['upper'] = upper;
        }
    }

    var data = [];

    // Series 1
    var d1 = analysisData[1];
    if (d1 !== null) {
        data.push({
            label: d1['name'],
            id: 'd1',
            data: d1['value'],
            lines: { show: true },
            color: analysisColors[0],
            highlightColor: '#fff'
        });
        if (show_deviation) {
            data.push({
                id: 'l1',
                data: d1['lower'],
                lines: { show: true, lineWidth: 0, fill: false},
                color: analysisColors[0],
                hoverable: false
            });
            data.push({
                id: 'u1',
                data: d1['upper'],
                lines: { show: true, lineWidth: 0, fill: 0.3},
                color: analysisColors[0],
                fillBetween: 'l1',
                hoverable: false
            });
        }
    }

    // Series 2
    var d2 = analysisData[2];
    if (d2 !== null) {
        data.push({
            label: d2['name'],
            id: 'd2',
            data: d2['value'],
            lines: { show: true },
            color: analysisColors[1],
            highlightColor: '#fff'
        });
        if (show_deviation) {
            data.push({
                id: 'l2',
                data: d2['lower'],
                lines: { show: true, lineWidth: 0, fill: false},
                color: analysisColors[1],
                hoverable: false
            });
            data.push({
                id: 'u2',
                data: d2['upper'],
                lines: { show: true, lineWidth: 0, fill: 0.3},
                color: analysisColors[1],
                fillBetween: 'l2',
                hoverable: false
            });
        }
    }

    // Series 3
    var d3 = analysisData[3];
    if (d3 !== null) {
        data.push({
            label: d3['name'],
            id: 'd3',
            data: d3['value'],
            lines: { show: true },
            color: analysisColors[2],
            highlightColor: '#fff'
        });
        if (show_deviation) {
            data.push({
                id: 'l3',
                data: d3['lower'],
                lines: { show: true, lineWidth: 0, fill: false},
                color: analysisColors[2],
                hoverable: false
            });
            data.push({
                id: 'u3',
                data: d3['upper'],
                lines: { show: true, lineWidth: 0, fill: 0.3},
                color: analysisColors[2],
                fillBetween: 'l3',
                hoverable: false
            });
        }
    }

    // Plot the graph
    analysisLineGraph = $.plot($('#lineGraph'), data, {
        grid: {
            backgroundColor: { colors: ['#363636', '#363636'] },
            hoverable: analysisGraphHoverable,
            clickable: analysisGraphHoverable
        },
        crosshair: { mode: 'x', color: '#F7941D' },
        xaxis: {
            minTickSize: 1,
            maxTickSize: 1,
            color: '#fff',
            // @todo: years currently hardcoded - replace by slider?
            min: 2005,
            max: 2015,
            tickDecimals: 0,
            tickFormatter: function(val, axis) {
                var v = val % 100;
                if (v < 10) {
                    return ("'0" + v);
                } else {
                    return ("'" + v);
                }
            },
            font: {
                weight: 'bold'
            }
        },
        yaxis: {
            color: '#fff',
            min: 1,
            max: 5,
            tickDecimals: 0,
            tickFormatter: function(val, axis) {
                var labelColor = {1: 'red', 2: 'orange', 3: 'yellow', 4: 'green', 5: 'darkgreen'};
                if (labelColor.hasOwnProperty(val)) {
                    return ('<div class="' + labelColor[val] + 'label">' + val + '</div>');
                } else {
                    return val.toString();
                }
            },
            labelWidth: 20,
            labelHeight: 20
        },
        legend: {
            show: false
        },
        colors: analysisColors
    });

    // Tooltip for data points
    if (analysisGraphHoverable) {
        $('#lineGraph').bind('plothover', function (event, pos, item) {
            analysisTooltip(pos, item, indicator_index, false);
        });
        $('#lineGraph').bind('plotclick', function (event, pos, item) {
            $('#lineGraph').unbind('click');
            if (item) {
                analysisTooltip(pos, item, indicator_index, true);
            }
            $('#lineGraph').click(function() {
                if (!analysisGraphHoverable) {
                    $('#lineGraph').unbind('click');
                    analysisGraphHoverable = true;
                    $('#lineGraph').click(function() {
                        $('#lineGraph').unbind('click');
                        analysisResetGraph();
                        analysisUpdateGraph();
                    });
                }
            });
        });
    }
}

function analysisTooltip(pos, item, indicator_index, click) {

    if (click) {
        if (analysisGraphHoverable) {
            analysisGraphHoverable = false;
            analysisUpdateGraph();
            analysisLineGraph.highlight(item.series, item.datapoint);
            $('#analysisTooltip').click(function() {
                analysisResetGraph();
                analysisUpdateGraph();
            });
        } else {
            return;
        }
    } else {
        if (!analysisGraphHoverable) {
            return;
        }
    }

    if (item) {
        if (analysisTooltipPreviousPoint != item.dataIndex) {
            analysisTooltipPreviousPoint = item.dataIndex;
            $('#analysisTooltip').remove();
            var year = item.datapoint[0].toFixed(0);
            var value = item.datapoint[1];
            var tooltip = '<div class="analysisTooltip"><h4>' + year + '</h4>';
            for (var n=1; n <= 3; n++) {
                var l = analysisLocation[n];
                if (l === null) {
                    continue;
                } else {
                    var location_id = l['id'];
                    try {
                        var val = analysisDataCache[location_id][year][indicator_index][0];
                        var dev = analysisDataCache[location_id][year][indicator_index][1];
                    }
                    catch(e) {
                        continue;
                    }
                    if (typeof val != 'undefined' && Math.abs(value - val) < 0.0001) {
                        name = l['name'].toLocaleUpperCase() + ' ' + l['level'].toLocaleUpperCase();
                        tooltip += '<h5 id="analysisSeries' + n + '" class="analysisSeriesLabel">' + name + '</h5>';

                        // @todo: i18n labels
                        var label_val = 'Overall Resilience';
                        var label_dev = 'Absolute Deviation';

                        tooltip += '<table>';
                        tooltip += '<tr><td class="ttleft">' + label_val + ':</td><td class="ttright">' + val.toFixed(0) + '</td></tr>';
                        tooltip += '<tr><td class="ttleft">' + label_dev + ':</td><td class="ttright">' + dev.toFixed(1) + '</td></tr>';
                        tooltip += '</table>';
                    }
                }
            }
            tooltip += '</div>';
            var offset = $('#lineGraphOuter').offset();
            var x = item.pageX - offset.left;
            var y = item.pageY - offset.top;
            analysisShowTooltip(x, y, tooltip);
            $('#analysisSeries1').css({color: analysisColors[0]});
            $('#analysisSeries2').css({color: analysisColors[1]});
            $('#analysisSeries3').css({color: analysisColors[2]});
            $('h5.analysisSeriesLabel').hover(function() {
                var id = this.id;
                series = id.substring(id.length - 1);
                if (analysisTooltipPreviousSeries == series) {
                    return;
                }
                analysisTooltipPreviousSeries = series;
                // Update the region indicator breakdown
                var loc = analysisLocation[series];
                var loc_id = loc['id'];
                name = loc['name'].toLocaleUpperCase() + ' ' + loc['level'].toLocaleUpperCase();
                var indicators = [];
                for (var i=1; i <= 10; i++) {
                    try {
                        var val = analysisDataCache[loc_id][year][i][0];
                        $('#indicatorRating'+i).text(val);
                    }
                    catch(e) {
                        $('#indicatorRating'+i).text('?');
                        continue;
                    }
                }
                $('#regionIndicators h3').text(name).css({color:analysisColors[series-1]});
                // Show the breakdown
                $('#regionIndicators').show();
            });
        }
    } else {
        $('#analysisTooltip').remove();
        analysisTooltipPreviousPoint = null;
    }
}

function analysisShowTooltip(x, y, contents) {
    // Render the tooltip at the data point
    $('<div id="analysisTooltip">' + contents + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y - 50,
        left: x + 10,
        border: '0',
        'padding': '10px',
        'padding-left': '28px',
        'min-height': '100px',
        'z-index': '501',
        background: 'transparent url(' + S3.Ap.concat('/static/img/whitearrow.png') + ') repeat scroll 0 0',
        color: '#000',
        opacity: 0.90
    }).appendTo('#lineGraphOuter').fadeIn(200);
}

// End
